package com;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javaBean.Log_into_javaBean;

public class Log_into_dao {

	public Collection<Log_into_javaBean> getAll() {
		Collection<Log_into_javaBean> LogVector = new ArrayList<Log_into_javaBean>();
		Connection conn = ConnectionPool.getConn();
		try {
			if (conn != null) {
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("select * from account");
				while (rs.next()) {
					Log_into_javaBean log = new Log_into_javaBean();
					log.setId(rs.getString(1));
					log.setPassword(rs.getString(2));
					LogVector.add(log);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return LogVector;
	}

	public static Log_into_javaBean selectBy(String id) {
		Log_into_javaBean log = null;
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = ConnectionPool.getConn();
		String sql = "select * from account where id='" + id + "'";
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			rs.next();
			log = new Log_into_javaBean();
			log.setId(rs.getString("id"));
			log.setPassword(rs.getString("password"));
			System.out.println("查询账号为'" + id + "'完毕！");
			ConnectionPool.close(rs, stmt, conn);
			return log;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		ConnectionPool.close(rs, stmt, conn);
		return log;
	}

	public boolean update(Log_into_javaBean log) {
		Statement stmt = null;
		int i = 0;
		Connection conn = ConnectionPool.getConn();
		try {
			stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
					ResultSet.CONCUR_UPDATABLE);
			String sql = "update account set password='" + log.getPassword()
					+ "' where id='" + log.getId() + "' ";
			i = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		ConnectionPool.close(stmt, conn);
		if (i > 0) {
			return true;
		} else {
			return false;
		}
	}

	public void delete(String id) throws Exception {
		Connection conn = ConnectionPool.getConn();
		Statement stmt = conn.createStatement();
		String sql = "delete from account where id='" + id + "'";
		stmt.executeUpdate(sql);
	}

	public void add(Log_into_javaBean log) throws Exception {
		Connection conn = ConnectionPool.getConn();
		PreparedStatement pstmt = conn
				.prepareStatement("insert into account(id,password)"
						+ "values(?,?)");
		pstmt.setString(1, log.getId());
		pstmt.setString(2, log.getPassword());
		pstmt.execute();

	}

}